package com.itheima.server.service;

import cn.hutool.core.collection.CollUtil;
import com.github.tobato.fastdfs.domain.conn.FdfsWebServer;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.itheima.dubbo.api.UserInfoApi;
import com.itheima.dubbo.api.mongo.FocusUserApi;
import com.itheima.dubbo.api.mongo.VideoApi;
import com.itheima.server.interceptor.UserHolder;
import com.tanhua.autoconfig.template.OssTemplate;
import com.tanhua.commons.utils.Constants;
import com.tanhua.model.domain.UserInfo;
import com.tanhua.model.mongo.FocusUser;
import com.tanhua.model.mongo.Video;
import com.tanhua.model.vo.PageResult;
import com.tanhua.model.vo.VideoVo;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.ibatis.jdbc.Null;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class SmallVideosService {

    @Autowired
    private OssTemplate ossTemplate;

    @Autowired
    private FastFileStorageClient client;

    @Autowired
    private FdfsWebServer webServer;

    @DubboReference
    private VideoApi videoApi;

    @DubboReference
    private UserInfoApi userInfoApi;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @DubboReference
    private FocusUserApi focusUserApi;

    /***
     * 上传小视频
     * @param videoThumbnail
     * @param videoFile
     * @throws IOException
     */

    //上传新视频的时候应该清楚缓存
    @CacheEvict(value = "videoLists",allEntries = true)
    public void saveVideo(MultipartFile videoThumbnail, MultipartFile videoFile) throws IOException {
        //1.先把视频上传到fastdfs
        String filename = videoFile.getOriginalFilename();
        String suffixName = filename.substring(filename.lastIndexOf(".") + 1); //获取拓展名
        StorePath storePath = client.uploadFile(videoFile.getInputStream(), videoFile.getSize(), suffixName, null);
        String videoUrl = webServer.getWebServerUrl()+storePath.getFullPath();
        //2. 把图片保存阿里的oss
        String picUrl = ossTemplate.upload(videoThumbnail.getOriginalFilename(), videoThumbnail.getInputStream());

        //3. 创建创建Video，设置参数
        Video video = new Video();
        video.setCreated(System.currentTimeMillis()); //视频的上传时间
        video.setUserId(UserHolder.getId()); //视频的上传人id
        video.setText("这是一个视频");  //视频的文字描述
        video.setPicUrl(picUrl);
        video.setVideoUrl(videoUrl);
        video.setLikeCount(0);
        video.setCommentCount(0);
        video.setLoveCount(0);

        //4. 保存视频
        videoApi.save(video);
    }

    /**
     * 视频列表
     * @param page
     * @param pagesize
     * @return
     */
    @Cacheable(value = "videoLists",key = "#page+'_'+#pagesize")
    public PageResult queryVideoList(Integer page, Integer pagesize) {
        //1. 得到视频分页列表
        PageResult pageResult = videoApi.findAll(page,pagesize);
        //2. 提取视频发布人的id
        List<Video> videoList = (List<Video>) pageResult.getItems();
        List<Long> userIds = CollUtil.getFieldValues(videoList, "userId", Long.class);
        //3. 批量查询发布人的用户信息
        Map<Long, UserInfo> userInfoMap = userInfoApi.findByIds(userIds);
        List<VideoVo> voList = new ArrayList<>();
        for (Video video : videoList) {
            UserInfo userInfo = userInfoMap.get(video.getUserId());
            VideoVo videoVo = VideoVo.init(userInfo, video);

            String key = Constants.FOCUS_USER_KEY+UserHolder.getId();
            String hashKey = String.valueOf(video.getUserId());
            if(redisTemplate.opsForHash().hasKey(key,hashKey)){
                videoVo.setHasFocus(1);
            }
            voList.add(videoVo);
        }
        pageResult.setItems(voList);

        //4.返回对象
        return pageResult;
    }

    /**
     * 关注视频用户
     * @param followUserId
     */
    public void userFocus(Long followUserId) {//1. 创建FocusUser
        FocusUser focusUser = new FocusUser();
        focusUser.setUserId(UserHolder.getId());
        focusUser.setFollowUserId(followUserId);
        focusUser.setCreated(System.currentTimeMillis());
        focusUserApi.save(focusUser);
        //在redis做已关注标记
        String key = Constants.FOCUS_USER_KEY+UserHolder.getId(); // FOCUS_USER_KEY_2
        String field = followUserId.toString(); //关注的用户
        redisTemplate.opsForHash().put(key,field,"1");

    }

    public void userUnFocus(Long followUserId) {
        Long userId = UserHolder.getId();
        focusUserApi.remove(userId,followUserId);

        String key = Constants.FOCUS_USER_KEY+UserHolder.getId(); // FOCUS_USER_KEY_2
        String field = followUserId.toString(); //关注的用户
        redisTemplate.opsForHash().delete(key,field);
    }
}